<template>
  <div class='scroll-box card-box'
       v-if="visible">
    <div class='pane-shell'>
      <el-dialog title="用户列表"
                 append-to-body
                 :visible.sync="visible"
                 :before-close="closeDialog"
                 :close-on-click-modal="false"
                 width="1300px"
                 :close-on-press-escape="false">
        <div v-loading='userloading'>
          <search @sumbit='sumbit'
                  :showSearchBtn='true'>
            <!--  搜索项 -->
            <template slot='form'>
              <el-form :inline='true'
                       @submit.native.prevent
                       :model='dataForm'
                       ref='dataForm'>
                <el-form-item prop='username'
                              :rules="stringRule(false)">
                  <el-input v-model='dataForm.username'
                            class='form-item'
                            clearable
                            placeholder='请输用户名称'></el-input>
                </el-form-item>
                <el-form-item prop='realName'
                              :rules="stringRule(false)">
                  <el-autocomplete v-model='dataForm.realName'
                                   class='form-item'
                                   clearable
                                   @select="handleSelect"
                                   :fetch-suggestions="querySearch"
                                   placeholder="姓名/用户名/首字母选择"></el-autocomplete>
                </el-form-item>
                <el-form-item prop="parentName">
                  <el-popover v-model.trim="deptListVisible"
                              ref="deptListPopover"
                              placement="bottom-start"
                              trigger="click">
                    <el-tree :data="deptList"
                             :props="{ label: 'name', children: 'children' }"
                             node-key="id"
                             ref="deptListTree"
                             :highlight-current="true"
                             :expand-on-click-node="false"
                             accordion
                             @current-change="deptListTreeCurrentChangeHandle">
                    </el-tree>
                  </el-popover>
                  <div class="dept-input">
                    <el-input v-model.trim="dataForm.parentName"
                              v-popover:deptListPopover
                              readonly
                              placeholder="所属部门">
                    </el-input>
                    <i class="el-icon-circle-close close"
                       @click="onDeptClose"
                       v-show="dataForm.parentName !== ''"></i>
                  </div>
                </el-form-item>
              </el-form>
            </template>
          </search>
          <el-table v-loading="dataListLoading"
                    :data="dataList"
                    border
                    height="350"
                    ref="table"
                    :row-key="getRowKey"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                    @selection-change="handleSelectionChange"
                    style="width: 100%;">
            <el-table-column type="selection"
                             v-if="selectType === 'checkout'"
                             width="55">
            </el-table-column>
            <el-table-column prop="username"
                             :label="$t('user.username')"
                             header-align="center"
                             align="center"></el-table-column>
            <el-table-column prop="realName"
                             min-width="100"
                             :label="$t('user.realName')"
                             header-align="center"
                             align="center"></el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination :current-page="page"
                           :page-sizes="[10, 20, 50, 100]"
                           :total="total"
                           layout="total, sizes, prev, pager, next"
                           @size-change="pageSizeChangeHandle"
                           @current-change="pageCurrentChangeHandle">
            </el-pagination>
          </div>
        </div>
        <template slot="footer">
          <el-button type="primary"
                     :loading="userloading"
                     @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
          <el-button @click="closeDialog()">{{ $t('cancel') }}</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import Search from '@/components/search/search'
import minFormValidate from '@/mixins/form-validate'
import mixinViewModule from '@/mixins/view-module'
export default {
  mixins: [mixinViewModule, minFormValidate],
  name: '',
  props: {
    selectType: {
      type: String,
      default: 'radio'
    }
  },
  data () {
    return {
      mixinViewModuleOptions: {
        activatedIsNeed: false,
        getDeptListURL: '/system/sysUser/getDeptInUser',
        getDataListURL: '/system/sysUser/getDataUseDept', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addOrUpdateURL: '', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteURL: '', // 删除接口，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      dataForm: {
        deptId: '',
        username: '',
        realName: '',
        parentName: ''
      },
      deptListVisible: false,
      deptList: [],
      userloading: false,
      visible: false,
      userInfo: ''
    }
  },
  components: { Search },
  computed: {},
  methods: {
    /**
     * @description: 校验字符串是否为字母汉字数字
     * @example: this.checkRule(123) this.checkRule('你好') this.checkRule('hello')
     * @param {string} str 要校验的字符串
     * @return {number} -1:非字母非文字非数字或不存在,1:字母,2:文字,3:数字
     */
    checkRule (str) {
      let results = -1
      if (str) {
        if (/^[a-zA-Z]*$/g.test(str)) { // 字母
          results = 1
        } else if (/^[\u4E00-\u9FA5]+$/.test(str)) { // 文字
          results = 2
        } else if (/^[0-9]*$/g.test(str)) { // 数字
          results = 3
        }
      }
      return results
    },
    querySearch (queryString, cb) {
      let str = ''
      if (this.checkRule(queryString) === -1 || this.checkRule(queryString) === 2) {
        str = `realName=${queryString}`
      } else if (this.checkRule(queryString) === 1) {
        if (!str.length === 1) return
        str = `initial=${queryString}`
      } else if (this.checkRule(queryString) === 3) {
        str = `username=${queryString}`
      }
      if (queryString === '') {
        str = ''
      }
      this.$http.get(`/system/sysUser/getByName?${str}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        let temp = res.data || []
        let restaurants = []
        temp.map((item) => {
          restaurants.push({
            value: item.username ? '' + item.username + '(' + item.realName + ')' : '',
            userId: item.id,
            name: item.realName,
            deptName: item.deptName,
            deptId: item.deptId,
            phone: item.phone,
            dept: item.dept
          })
        })
        // 调用 callback 返回建议列表的数据
        cb(restaurants)
      })
    },
    handleSelect (item) {
      this.dataForm.realName = item.name
      this.sumbit()
    },
    sumbit () {
      this.userloading = true
      this.getPageInit().then(() => {
        this.userloading = false
      })
    },
    getRowKey (row) {
      return row.id
    },
    init (data) {
      data = data || {}
      this.userInfo = ''
      this.userInfoArr = []
      this.userloading = true
      this.dataForm.deptId = data.deptId
      this.getDeptList()
      this.getDataList().then(() => {
        this.userloading = false
        this.$nextTick(() => {
          if (this.selectType === 'checkout') {
            this.$refs.table.store.states.selection = data.list
            this.$refs.table.store.updateSelectionByRowKey()
          }
        })
      })
      this.visible = true
    },
    onDeptClose () {
      this.dataForm.parentName = ''
      this.dataForm.deptId = ''
    },
    getDeptList () {
      // 获取部门列表
      this.getDataList({ url: this.mixinViewModuleOptions.getDeptListURL, paramData: {} }).then(res => {
        if (res.code !== 0) { return }
        this.deptList = res.data
        if (!res.data.length) {
          this.deptList.push({
            id: 0,
            name: this.$t('dept.parentNameDefault')
          })
        }
      })
    },
    // 上级部门树, 选中
    deptListTreeCurrentChangeHandle (data) {
      this.dataForm.username = ''
      this.dataForm.userId = ''
      this.dataForm.deptId = data.id
      this.dataForm.parentName = data.name
      this.deptListVisible = false
    },
    closeDialog () {
      this.userInfo = ''
      this.userInfoArr = []
      this.visible = false
    },
    dataFormSubmitHandle () {
      if (this.userInfo === '' && this.selectType === 'radio') {
        return this.$message.warning('请选择用户')
      }

      if (this.userInfoArr.length === '' && this.selectType === 'checkout') {
        return this.$message.warning('请选择用户')
      }
      if (this.selectType === 'radio') {
        this.$emit('callBack', this.userInfo)
      } else {
        this.$emit('callBack', this.userInfoArr)
      }
      this.visible = false
    },
    // 单选
    handleCurrentChange (val) {
      this.userInfo = Object.assign({}, {}, val)
    },
    // 多选
    handleSelectionChange (val) {
      this.userInfoArr.splice(0, this.userInfoArr.length, ...val)
    }
  }
}
</script>

<style lang="scss" scoped>
.pagination {
  text-align: right;
  margin-top: 5px;
}
.dept-input {
  width: 100%;
  position: relative;
  .close {
    position: absolute;
    right: 10px;
    top: 13px;
    font-size: 16px;
    color: #858585;
    cursor: pointer;
    background-color: white;
  }
}
</style>
